<template>
  <div class="container">
    <h2>用户管理</h2>
    
    <div class="user-form">
      <h3>{{ userModule.editingUser ? '编辑用户' : '添加新用户' }}</h3>
      <div class="form-group">
        <label for="userName">姓名:</label>
        <input id="userName" v-model="userModule.newUser.name" placeholder="请输入姓名" />
      </div>
      <div class="form-group">
        <label for="userEmail">邮箱:</label>
        <input id="userEmail" v-model="userModule.newUser.email" placeholder="请输入邮箱" type="email" />
      </div>
      <button @click="saveUser" class="btn">{{ userModule.editingUser ? '更新用户' : '添加用户' }}</button>
      <button v-if="userModule.editingUser" @click="cancelEdit" class="btn-warning">取消编辑</button>
    </div>
    
    <div class="user-list-container">
      <h3>用户列表</h3>
      <div class="search-box">
        <input v-model="appModule.state.userSearch" placeholder="搜索用户..." />
      </div>
      <button @click="loadUsers" class="btn">刷新用户列表</button>
      <div class="loading" v-if="appModule.state.loading">加载中...</div>
      <div v-else>
        <div class="user-item" v-for="user in filteredUsers" :key="user.id">
          <div class="user-details">
            <strong>{{ user.id }} - {{ user.name }}</strong> ({{ user.email }})
          </div>
          <div class="user-actions">
            <button @click="editUser(user)" class="btn-warning btn-sm">编辑</button>
            <button @click="deleteUser(user.id)" class="btn-danger btn-sm">删除</button>
          </div>
        </div>
        <div v-if="filteredUsers.length === 0">暂无用户数据</div>
      </div>
    </div>
  </div>
</template>

<script>
export default {
  props: ['appModule'],
  data() {
    return {
      // 组件数据直接引用应用模块
    };
  },
  computed: {
    userModule() {
      return this.appModule.userModule;
    },
    filteredUsers() {
      return this.appModule.getFilteredUsers();
    }
  },
  methods: {
    async loadUsers() {
      try {
        await this.userModule.loadUsers();
      } catch (error) {
        this.appModule.state.error = error.message;
      }
    },
    async saveUser() {
      this.appModule.state.error = '';
      
      // 验证输入
      if (!this.userModule.newUser.name || !this.userModule.newUser.email) {
        this.appModule.state.error = '请填写姓名和邮箱';
        return;
      }
      
      try {
        await this.userModule.saveUser(this.userModule.newUser);
        this.userModule.setEditingUser(null);
      } catch (error) {
        this.appModule.state.error = error.message;
      }
    },
    editUser(user) {
      this.userModule.setEditingUser(user);
    },
    cancelEdit() {
      this.userModule.setEditingUser(null);
    },
    async deleteUser(userId) {
      if (!confirm('确定要删除这个用户吗？')) {
        return;
      }
      
      try {
        await this.userModule.deleteUser(userId);
      } catch (error) {
        this.appModule.state.error = error.message;
      }
    }
  }
};
</script>
</file>